package com.lbj.googleplay.googleplay100.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.lbj.googleplay.googleplay100.R;
import com.lbj.googleplay.googleplay100.utils.LogUtils;

/*
*
* 自定义控件,可以根据图片的原始比例绝对布局高度
* */
public class RatioLayout extends FrameLayout {

    private  float ratio;//图片的宽高比

    public RatioLayout(@NonNull Context context) {
        super(context);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        getRatio(context,attrs);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getRatio(context,attrs);
    }

    //获取xml文件传递进来的属性值
    private void getRatio(Context context, AttributeSet attrs){
        //获取xml文件传递进来的属性值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
        ratio = typedArray.getFloat(R.styleable.RatioLayout_ratio, -1);
        typedArray.recycle();
        LogUtils.v("ratio==="+ratio);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //1.获取当前宽度
        int  width= MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        //2.根据宽度和ratio计算出控件的高度
        if (ratio>0&&widthMode==MeasureSpec.EXACTLY&&heightMode==MeasureSpec.UNSPECIFIED){
            //图片宽度=控件宽度-左边距-右边距
            int imageWidth = width-getPaddingLeft()-getPaddingRight();
            //图片高度=图片宽度/ratio比例
            int imageHeight = (int) (imageWidth/ratio);
            //控件高度=图片高度+上下内边距
            height = imageHeight+getPaddingTop()+getPaddingBottom();
            //根据最新的高度来重新生成heightMeasureSpec,此时高度设为确定模式
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
        }
        //3.按照最新高度,重新测量控件
        
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
